package com.hanson.service;

import com.hanson.entity.FileBean;
import com.hanson.entity.FileTypeBean;
import com.hanson.mapper.FileBeanMapper;
import com.hanson.mapper.FileTypeBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class FileService {
    @Autowired
    private FileTypeBeanMapper fileTypeBeanMapper;
    @Autowired
    private FileBeanMapper fileBeanMapper;

    public void addFileType(FileTypeBean fileTypeBean) {
        fileTypeBean.setPid(0);
        fileTypeBeanMapper.insert(fileTypeBean);
    }

    public void modifyFileType(FileTypeBean fileTypeBean) {
        fileTypeBean.setPid(0);
        fileTypeBeanMapper.updateByPrimaryKey(fileTypeBean);
    }

    public void deleteFileType(int id) {
        fileTypeBeanMapper.deleteByPrimaryKey(id);
    }

    public FileTypeBean selectFileType(Integer id){
        return fileTypeBeanMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteImage(String imageId){
        if(!StringUtils.isEmpty(imageId)){
            Arrays.stream(imageId.split(",")).forEach(c->{
                if(!StringUtils.isEmpty(c)){
                    fileBeanMapper.deleteByPrimaryKey(Integer.parseInt(c));
                }
            });
        }
    }

    public void addFile(String url,String fileName,int fileSize,Integer pid){
        FileBean fileBean = new FileBean();
        fileBean.setCreateDate(new Date());
        fileBean.setFilePath(url);
        fileBean.setSfilePath(url);
        fileBean.setPid(pid);
        fileBean.setFileName(fileName);
        fileBean.setFileSize(fileSize);
        fileBean.setModuleType(1);
        fileBeanMapper.insert(fileBean);
    }

    public List<FileBean> getImageList(int pid,int page,int limit){
        return fileBeanMapper.selectPage(pid,(page-1)*limit,limit);
    }

    public int getImageCount(int pid){
        return fileBeanMapper.selectCount(pid);
    }

    public List<FileTypeBean> getAllFileTypes(String search) {
        List<FileTypeBean> list = fileTypeBeanMapper.selectAll(search, 0);
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(c -> {
                List<FileTypeBean> child = fileTypeBeanMapper.selectAll(null, c.getId());
                if (!CollectionUtils.isEmpty(child)) {
                    c.getChild().addAll(child);
                }
            });
        }
        return list;
    }
}
